<template>
  <div class="layout-container">
    <!-- 侧边栏 -->
    <Sidebar 
      :history-list="historyList" 
      @open-history="handleOpenHistory"
    />
    
    <!-- 主内容区 -->
    <div class="main-wrapper">
      <!-- 头部 -->
      <Header />
      
      <!-- 路由视图：渲染热点雷达/创作工厂 -->
      <div class="content-area">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Sidebar from './Sidebar.vue';
import Header from './Header.vue';
import { useRouter } from 'vue-router';
import { STORAGE_KEYS } from '../utils/constants';

const router = useRouter();
// 历史记录数据（从本地存储读取）
const historyList = ref([]);

// 初始化历史记录
const loadHistory = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEYS.HISTORY_RECORD);
    if (saved) {
      const history = JSON.parse(saved);
      historyList.value = history.map(item => {
        if (!item.id) {
          return { ...item, id: Date.now().toString() + Math.random().toString(36).substr(2, 9) }
        }
        return item;
      });
    }
  } catch (error) {
    console.warn('无法访问localStorage，使用空历史记录:', error);
    historyList.value = [];
  }
};

onMounted(() => {
  loadHistory();
  // 监听历史记录更新事件
  window.addEventListener('history-updated', () => {
    loadHistory();
  });
});


// 处理从侧边栏打开历史记录
const handleOpenHistory = (item) => {
  try {
    if (item.platforms) {
      localStorage.setItem('selectedPlatforms', JSON.stringify(item.platforms))
    }
  } catch (error) {
    console.warn('无法访问localStorage:', error);
  }
  router.push({
    path: '/creation',
    query: { title: item.title, id: item.id }
  });
};
</script>

<style scoped>
.layout-container {
  display: flex;
  height: 100vh;
  width: 100vw; 
}

.main-wrapper {
  flex: 1; 
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border-left: 1px solid #eee; 
}

.content-area {
  flex: 1;
  overflow-y: auto; 
  padding: 20px;
  background-color: #f9fafb;
}
</style>
